package com.sort;

import java.util.Arrays;

/**
 * 插入排序
 * 作者：swk
 * 时间：
 * 公司：
 **/
public class InsertSort {
    public static long count = 0;

    public static void main(String[] args) {
        int[] arr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr[i] = (int) (Math.random() * 8000000);
        }
        long beginTime = System.currentTimeMillis();
        insertSort(arr);
        long endTime = System.currentTimeMillis();
        //System.out.println("排序后结果：" + Arrays.toString(arr));
        System.out.println("耗时：" + (endTime - beginTime));
        System.out.println("循环次数：" + count);
        count = 0;
    }

    public static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int insertVal = arr[i];
            int insertIndex = i - 1;
            while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
                arr[insertIndex + 1] = arr[insertIndex];
                insertIndex--;
                count++;
            }
            if (insertIndex + 1 != i) {
                arr[insertIndex + 1] = insertVal;
            }
            //System.out.println("第" + i + "轮排序结果：" + Arrays.toString(arr));

        }
    }
}
